import { element } from 'protractor'
import { Component, OnInit } from '@angular/core'
import { JsonApiService } from 'app/core/api/json-api.service' //http请求配置引入
import { config } from '../../shared/smartadmin.config'

declare var $: any
declare var Viewer: any
@Component({
  selector: 'sa-hz-statistics',
  templateUrl: './hz-statistics.component.html'
})
export class HZStatisticsComponent implements OnInit {
  tableData: any[] = [] //table数据
  totalCount: number = 0 //分页总条数
  curPage: number = 1 //分页当前页
  pageSize: number = 10 //内置的分页每页条数
  searchKey: string = '' //搜索keyword
  positionList: any[] = [] //搜索收运点位数据
  importBtn = false // 控制导入按钮权限
  tableQueryitem = {
    startTime: '', //开始时间
    endTime: '', //结束时间
    deviceId: '', //设备ID
    carNumber: '',
    code: '',
    searchKey: '' //搜索keyword
  }
  constructor(private jsonApiService: JsonApiService) {}
  ngOnInit() {
	this.initBtn()
	this.initPositionList().then(()=>{
		this.selectPosition();
	});
    this.load()
  }

  //get权限按钮数据
  initBtn() {
    const btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_statistics:hzStatistics')))
    if (!btnData) {
      return
    }
    for (let item of btnData) {
      if (item.sourceKey === 'statistics:hzStatistics:import' && item.parentId) {
        this.importBtn = true
      }
    }
  }

  getSelectTableTime(time) {
    this.tableQueryitem.startTime = time.startTime
    this.tableQueryitem.endTime = time.endTime
  }
  getSelectCarInfo(val) {
    this.tableQueryitem.deviceId = val.deviceId
    this.tableQueryitem.carNumber = val.carNumber
  }

  //擦除用户所选值
  delPosition() {
    this.tableQueryitem.code = ''
    //采用简单粗暴的方法清除;官方推荐的方法失效
    var str = $("<span class='select2-selection__placeholder'>请选择</span>")
    $('#positionSelect2').val('')
    $('#select2-positionSelect2-container').empty()
    $('#select2-positionSelect2-container').attr('title', '')
    $('#select2-positionSelect2-container').prepend(str)
    this.load()
  }
  //初始化select2 选项
  selectPosition() {
    var that = this
    System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
      System.import('assets/js/select2-zh-CN.js').then(() => {
        $('#positionSelect2')
          .select2({
            language: 'zh-CN',
            placeholder: '请选择',
            allowClear: true,
            data: this.positionList //为Select添加数据
          })
          .on('select2:select', function (e) {
            var data = e.params.data
            that.tableQueryitem.code = data.id
          })
      })
    })
  }
  //拉取
  initPositionList() {
    return new Promise(resolve => {
      this.jsonApiService
        .http('fuTaiRubbishCollectionPoint/queryFuTaiRubbishCollectionPointList.html', null)
        .subscribe(data => {
          if (data.success) {
            this.positionList = data.data
              ? data.data.map(item => ({
                  id: item.code,
                  text: item.name
                }))
              : []
          }
          resolve(true)
        })
    })
  }

  //导出报表
  export_totle() {
    var parameters = {
      deviceId: this.tableQueryitem.deviceId,
      startTime: this.tableQueryitem.startTime,
      endTime: this.tableQueryitem.endTime
    }
    let timeCheck = common.correctTime(parameters)
    if (!timeCheck.status) {
      this.jsonApiService.message(timeCheck.message)
      return
    }
    common.exprotDataFile(parameters, 'param', config.BaseURL + 'weightStatistics/exportWeightDataStatistics.html')
  }
  //时间转化
  getTime(date) {
    var year = date.getFullYear()
    var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
    var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()

    return year + '-' + month + '-' + day
  }
  //初始化加载list数据
  load() {
    let timeCheck = common.correctTimeParams(this.tableQueryitem.startTime, this.tableQueryitem.endTime, 0)
    if (!timeCheck.status) {
      this.jsonApiService.message(timeCheck.message)
      return
    }
    let data = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: {
        deviceId: this.tableQueryitem.deviceId,
        //				companyId:this.tableQueryitem.companyId,
        // startTime:this.tableQueryitem.startTime,
        // endTime:this.tableQueryitem.endTime,
        code: this.tableQueryitem.code,
        searchKey: this.tableQueryitem.searchKey
      }
    }
    let reqdata = 'gridPager=' + JSON.stringify(data)
    this.jsonApiService
      .http('fuTaiRubbishCollectionPoint/queryFuTaiRubbishCollectionStatisticsInfoPage.html', reqdata)
      .subscribe(result => {
        if (!result.isSuccess) {
          this.jsonApiService.message(result.message)
          return
        }
        //			for(let item of result.exhibitDatas){
        //				item.weight=common.twoDecimal(item.weight);
        //			}
        this.tableData = result.exhibitDatas
        this.totalCount = result.recordCount
      })
  }
  //刷新
  refresh() {
    this.load()
  }
  //查询
  table_search() {
    this.curPage = 1
    this.searchKey = common.stringTrim(this.searchKey)
    this.load()
  }
  //分页回调
  paginate(e) {
    this.curPage = e.page + 1
    this.pageSize = e.rows
    this.load()
  }
  ngOnDestroy() {
    document.onclick = null
  }

  // ---------------  导入部分 ---------------//
  fileToUpload: File = null //上传文件回调参数
  fileUp: string = ''
  //导入submit
  submitData(val) {
    let postParam = new FormData()
    postParam.append('file', this.fileToUpload)
    if (!this.fileToUpload) {
      this.jsonApiService.message('请上传文件')
      return false
    }
    this.jsonApiService
      .form_http('fuTaiRubbishCollectionPoint/uploadFuTaiRubbishCollectionPoint.html', postParam)
      .subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          val.hide()
          this.fileToUpload = null
          this.load()
        }
      })
  }
  //下载模板
  load_module() {
    var elemIF = document.createElement('iframe')
    elemIF.src = config.BaseURL + 'resources/template/huZhouPoint.xlsx'
    elemIF.style.display = 'none'
    document.body.appendChild(elemIF)
  }
  clearFile() {
    this.fileUp = ''
  }
  //文件上传change回调
  fileChange(files: FileList) {
    this.fileToUpload = files.item(0)
    const isEXCEL =
      this.fileToUpload.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
      this.fileToUpload.type === 'application/vnd.ms-excel'
    if (!isEXCEL) {
      this.jsonApiService.message('上传文件只能是 excel格式!')
      this.fileToUpload = null
      return
    }
  }
  importUp(modal) {
    this.fileToUpload = null
    modal.show()
  }
  cancelUp(val) {
    val.hide()
    this.fileToUpload = null
  }

  // ---------------  查看收运桶数部分 ---------------//
  barrelAgeTableData: any[] = []

  viewBarrelAge(row, modal) {
    modal.show()
    const data = {
      deviceId: row.deviceId,
      startTime: row.startTime,
      endTime: row.endTime
    }
    let reqStr = ''
    for (let k in data) {
      if (!reqStr) {
        reqStr += k + '=' + data[k]
      } else {
        reqStr += '&' + k + '=' + data[k]
      }
    }
    this.jsonApiService
      .http_get('fuTaiRubbishCollectionPoint/queryFuTaiRfidWeightList.html?' + reqStr)
      .subscribe(res => {
        this.barrelAgeTableData = res.data
      })
  }
  // ---------------  查看抓拍照片明细部分 ---------------//
  captureTableData: any[] = []

  viewer: any = null

  viewCapture(row, modal) {
    modal.show()
    const data = {
      deviceId: row.deviceId,
      startTime: row.startTime,
      endTime: row.endTime
    }
    let reqStr = ''
    for (let k in data) {
      if (!reqStr) {
        reqStr += k + '=' + data[k]
      } else {
        reqStr += '&' + k + '=' + data[k]
      }
    }
    this.jsonApiService
      .http_get('fuTaiRubbishCollectionPoint/queryFuTaiRubbishPhotoList.html?' + reqStr)
      .subscribe(res => {
        this.captureTableData = res.data
      })
  }

  //显示图片组件
  showImg(e) {
    if (this.viewer) {
      this.viewer.destroy()
    }
    this.viewer = new Viewer(e.target)
    this.viewer.show()
  }

  // 关闭弹框
  clickModalHide(modal) {
    modal.hide()
  }
}
